"use client"

import { useState, useEffect } from "react"
import type { GameState } from "./types/game"
import { LEVELS } from "./config/levels"
import { MainMenu } from "./components/main-menu"
import { GameLevel } from "./components/game-level"
import { OpeningCG } from "./components/opening-cg"

export default function MedievalTrialGame() {
  const [gameState, setGameState] = useState<GameState>({
    currentLevel: "opening",
    completedLevels: [],
    persuasionValues: {
      guard: LEVELS.guard.initialPersuasion,
      minister: LEVELS.minister.initialPersuasion,
      king: LEVELS.king.initialPersuasion,
    },
    npcResponse: "",
    playerInput: "",
  })

  // Load game state from localStorage
  useEffect(() => {
    const saved = localStorage.getItem("medieval-trial-game")
    if (saved) {
      try {
        const parsedState = JSON.parse(saved)
        setGameState((prev) => ({ ...prev, ...parsedState, currentLevel: "menu" }))
      } catch (error) {
        console.error("Failed to load game state:", error)
      }
    }
  }, [])

  // Save game state to localStorage
  useEffect(() => {
    localStorage.setItem(
      "medieval-trial-game",
      JSON.stringify({
        completedLevels: gameState.completedLevels,
        persuasionValues: gameState.persuasionValues,
      }),
    )
  }, [gameState.completedLevels, gameState.persuasionValues])

  const handleLevelSelect = (levelId: string) => {
    setGameState((prev) => ({
      ...prev,
      currentLevel: levelId as any,
    }))
  }

  const handlePersuasionChange = (levelId: string, value: number) => {
    setGameState((prev) => ({
      ...prev,
      persuasionValues: {
        ...prev.persuasionValues,
        [levelId]: value,
      },
    }))
  }

  const handleLevelComplete = (levelId: string) => {
    setGameState((prev) => ({
      ...prev,
      completedLevels: [...prev.completedLevels.filter((id) => id !== levelId), levelId],
      currentLevel: "menu",
    }))
  }

  const handleLevelRestart = (levelId: string) => {
    const level = LEVELS[levelId]
    setGameState((prev) => ({
      ...prev,
      persuasionValues: {
        ...prev.persuasionValues,
        [levelId]: level.initialPersuasion,
      },
    }))
  }

  const handleBackToMenu = () => {
    setGameState((prev) => ({
      ...prev,
      currentLevel: "menu",
    }))
  }

  const handleOpeningComplete = () => {
    setGameState((prev) => ({
      ...prev,
      currentLevel: "menu",
    }))
  }

  if (gameState.currentLevel === "opening") {
    return <OpeningCG onComplete={handleOpeningComplete} />
  }

  if (gameState.currentLevel === "menu") {
    return <MainMenu completedLevels={gameState.completedLevels} onLevelSelect={handleLevelSelect} />
  }

  const currentLevelId = gameState.currentLevel
  const currentPersuasion = gameState.persuasionValues[currentLevelId as keyof typeof gameState.persuasionValues]

  return (
    <GameLevel
      levelId={currentLevelId}
      persuasionValue={currentPersuasion}
      onPersuasionChange={(value) => handlePersuasionChange(currentLevelId, value)}
      onComplete={() => handleLevelComplete(currentLevelId)}
      onRestart={() => handleLevelRestart(currentLevelId)}
      onBack={handleBackToMenu}
    />
  )
}
